<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <el-button type="primary" icon="el-icon-search" @click="TableSearch">搜 索</el-button>
                <el-button @click="Reset" icon="el-icon-delete">重 置</el-button>
            </div>
            <div class="tb-body">
                <el-form ref="searchFormRef" :model="searchForm" :inline="true" label-width="120px" :style="`flex:1;`">
                    <el-form-item label="开始日期">
                        <el-date-picker v-model="searchForm.BeginDateRange" type="datetimerange" start-placeholder="开始开始日期"
                            end-placeholder="结束开始日期" :default-time="['00:00:00']" value-format="yyyy-MM-dd HH:mm">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束日期">
                        <el-date-picker v-model="searchForm.EndDateRange" type="datetimerange" start-placeholder="开始结束日期"
                            end-placeholder="结束结束日期" :default-time="['00:00:00']" value-format="yyyy-MM-dd HH:mm">
                        </el-date-picker>
                    </el-form-item>
                    

                    <el-form-item label="班级">
                        <el-paged-select url="/Organization/List" columnName="Name" columnValue="Id"
                            v-model="searchForm.OrganizationId">
                        </el-paged-select>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <el-dialog title="考勤设置编辑对话框" :visible.sync="editorShow" width="80%" :lock-scroll="true" height="800px">
            <el-form v-if="editorShow" ref="editModalForm" :rules="editModalFormRules" :model="formData"
                label-width="140px" size="mini">
                <el-row :gutter="10">

                    <el-col :span="12">
                        <el-form-item label="起始日期" prop="BeginDate">
                            <el-date-picker 
                                v-model="formData.BeginDate" 
                                align="right" 
                                type="date" 
                                placeholder="选择起始日期"
                                value-format="yyyy-MM-dd" 
                                format="yyyy-MM-dd"
                                @change="updateEndDate">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束日期" prop="EndDate">
                            <el-date-picker 
                                v-model="formData.EndDate" 
                                align="right" 
                                type="date" 
                                placeholder="选择结束日期"
                                value-format="yyyy-MM-dd" 
                                format="yyyy-MM-dd"> 
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="签到开始时间" prop="AmBeginHMS">
                            <el-time-picker
                                v-model="formData.AmBeginHMS"
                                placeholder="选择时间"
                                format="HH:mm"
                                value-format="HH:mm"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="签到结束时间" prop="AmEndHMS">
                            <el-time-picker
                                v-model="formData.AmEndHMS"
                                placeholder="选择时间"
                                format="HH:mm"
                                value-format="HH:mm"
                                :picker-options="{
                                    selectableRange: (formData.AmBeginHMS ? formData.AmBeginHMS + ':00 - 23:59:59' : '00:00:00 - 23:59:59')
                                }"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="班级" prop="OrganizationId">
                            <el-paged-select url="/Organization/List" columnName="Name" columnValue="Id"
                                v-model="formData.OrganizationId">
                            </el-paged-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="课程名称" prop="CourseName">
                            <el-input v-model="formData.CourseName" placeholder="请输入课程名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="签到类型" prop="CheckType">
                            <el-select v-model="formData.CheckType" placeholder="请选择签到类型">
                                <el-option label="人脸打卡" value="face"></el-option>
                                <el-option label="直接打卡" value="normal"></el-option>
                                <el-option label="位置打卡" value="location"></el-option>
                                <el-option label="扫码打卡" value="qrcode"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="签到内容" prop="CheckContent">
                            <el-input v-model="formData.CheckContent" placeholder="请输入二维码文字"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row type="flex" justify="end" align="bottom">
                    <el-form-item>
                        <el-button type="primary" plain @click="CreateOrEditForm()">确 定</el-button>
                        <el-button @click="editorShow = false">取 消</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
        </el-dialog>

        <el-dialog title="签到情况统计" :visible.sync="checkStatDialogVisible" width="50%" :lock-scroll="true">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <el-tabs v-model="activeTab" @tab-click="handleTabClick" style="flex: 1;">
                    <el-tab-pane label="全部" name="all"></el-tab-pane>
                    <el-tab-pane label="已签到" name="checked"></el-tab-pane>
                    <el-tab-pane label="未签到" name="unchecked"></el-tab-pane>
                    <el-tab-pane label="迟到" name="late"></el-tab-pane>
                    <el-tab-pane label="请假" name="leave"></el-tab-pane>
                </el-tabs>
                <el-button type="primary" style="margin-bottom: 15px;" size="small" @click="exportCheckDatas">导出数据</el-button>
            </div>
            <div class="check-stat-container">
                <div v-for="(item, index) in filteredCheckStatList" :key="index" class="user-stat-item">
                    <div class="avatar-container" 
                        v-if="activeTab === 'unchecked'"
                        @click="showStatusChangeDialog(item)"
                        title="点击修改签到状态">
                        <el-avatar :size="60" :src="item.ImageUrls || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                        <div class="stat-badge" :class="{
                            'checked': item.CheckStatus === 1,
                            'unchecked': item.CheckStatus === 0,
                            'late': item.CheckStatus === 2,
                            'leave': item.CheckStatus === 3
                        }"></div>
                    </div>
                    <div class="avatar-container" v-else>
                        <el-avatar :size="60" :src="item.ImageUrls || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                        <div class="stat-badge" :class="{
                            'checked': item.CheckStatus === 1,
                            'unchecked': item.CheckStatus === 0,
                            'late': item.CheckStatus === 2,
                            'leave': item.CheckStatus === 3
                        }"></div>
                    </div>
                    <div class="user-name">{{ item.Name }}</div>
                </div>
            </div>
        </el-dialog>

        <el-dialog title="二维码" :visible.sync="qrcodeDialogVisible" width="30%" :center="true">
            <div style="text-align: center;">
                <qrcode-vue :value="currentQRCode" :size="200" level="H"></qrcode-vue>
            </div>
        </el-dialog>

        <el-dialog title="修改签到状态" :visible.sync="statusChangeDialogVisible" width="30%" :center="true">
            <el-form :model="statusChangeForm" label-width="80px">
                <el-form-item label="新状态">
                    <el-radio-group v-model="statusChangeForm.newStatus">
                        <el-radio :label="2">迟到</el-radio>
                        <el-radio :label="3">请假</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="statusChangeDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitStatusChange">确 定</el-button>
            </div>
        </el-dialog>

        <data-table ref="tableId" url="/CheckSetting/List" :column="dataColum">
            <template v-slot:header>
                <el-button type="primary" plain icon="el-icon-edit" @click="ShowEditModal()">新 增</el-button>
                <el-button type="danger" plain icon="el-icon-delete" @click="ShowBatchDeleteModal()">批 量 删 除</el-button>
            </template>
            <template v-slot:operate="scope">
                <el-button type="text" v-if="scope.row.CheckType == 'qrcode'" @click="showQRCode(scope.row)">二维码</el-button>
                <el-button type="text" @click="showCheckStatDialog(scope.row)">查看签到情况</el-button>
                <el-button type="text" @click="ShowEditModal(scope.row.Id)">修 改</el-button>
                <el-button type="text" @click="ShowDeleteModal(scope.row.Id)">删 除</el-button>
            </template>
            <template v-slot:CheckType="scope">
                {{ scope.row.CheckType === 'face' ? '人脸打卡' :
                   scope.row.CheckType === 'normal' ? '直接打卡' :
                   scope.row.CheckType === 'location' ? '位置打卡' :
                   scope.row.CheckType === 'qrcode' ? '扫码打卡' : scope.row.CheckType }}
            </template>
        </data-table>
    </div>
</template>

<script>
import store from '@/store';
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
import { mapGetters } from 'vuex';
import QrcodeVue from 'qrcode-vue';

export default {
    name: "CheckSettingList",
    components: {
        QrcodeVue
    },
    computed: {
        ...mapGetters([
            'name', 'roleTypeFormat', 'avatar', 'userId', 'loginTimePeriod', "user", 'userId', 'roleType'
        ]),
        filteredCheckStatList() {
            switch (this.activeTab) {
                case 'checked':
                    return this.checkStatList.filter(item => item.CheckStatus === 1);
                case 'unchecked':
                    return this.checkStatList.filter(item => item.CheckStatus === 0);
                case 'late':
                    return this.checkStatList.filter(item => item.CheckStatus === 2);
                case 'leave':
                    return this.checkStatList.filter(item => item.CheckStatus === 3);
                default:
                    return this.checkStatList;
            }
        }
    },
    data() {
        return {
            lock: 0,
            searchForm: {},
            activeTab: 'all',
            currentCheckSettingId: 0,
            currentOraganizationId: 0,
            dataColum: [
                { key: "Id", hidden: true },
                { key: "BeginDate", title: "开始日期" },
                { key: "EndDate", title: "结束日期" },
                { key: "CourseName", title: "课程名称" },
                { key: "AmBeginHMS", title: "签到开始时间" },
                { key: "AmEndHMS", title: "签到结束时间" },
                { key: "OrganizationId", hidden: true },
                { key: "OrganizationDto.Name", title: "班级", type: store.getters.columnType.SHORTTEXT },
                {
                    key: "CheckType",
                    title: "签到类型",
                    type: store.getters.columnType.CUSTOM,
                },
                {
                    key: "CheckContent",
                    title: "签到内容"
                },
                { title: "操作", width: "300px", type: store.getters.columnType.USERDEFINED },
            ],
            editModalFormRules: {
                "BeginDate": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "EndDate": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "AmBeginHMS": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "AmEndHMS": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "PmBeginHMS": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "PmEndHMS": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "OrganizationId": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "CourseName": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
                "CheckType": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],
            },
            formData: {
                BeginDate: null,
                EndDate: null,
                AmBeginHMS: null,
                AmEndHMS: null,
                PmBeginHMS: null,
                PmEndHMS: null,
                OrganizationId: null,
                CourseName: null,
                CheckType: null,
            },
            editorShow: false,
            checkStatList: [],
            checkStatDialogVisible: false,
            qrcodeDialogVisible: false,
            currentQRCode: '',
            statusChangeDialogVisible: false,
            statusChangeForm: {
                newStatus: 2,
                userId: null
            },
            currentEditingUser: null
        };
    },
    created() {

    },
    methods: {
        async ShowEditModal(Id) {
            this.formData = {
                BeginDate: null,
                EndDate: null,
                AmBeginHMS: null,
                AmEndHMS: null,
                PmBeginHMS: null,
                PmEndHMS: null,
                OrganizationId: null,
            };

            if (Id) {
                let { Data } = await this.$Post(`/CheckSetting/Get`, { Id: Id });
                this.formData = Data;
            }
            this.formData.Behavior = null;
            this.formData.IsEdit = Id != undefined;

            this.editorShow = true;
        },
        async CreateOrEditForm() {
            if (this.lock == 1) return;
            this.$refs.editModalForm.validate(async valid => {
                if (valid) {
                    this.lock = 1;
                    var { Success } = await this.$PostLoading(`/CheckSetting/CreateOrEdit`, this.formData);
                    this.lock = 0;
                    if (Success) {
                        this.editorShow = false;
                        this.$refs.tableId.reload();
                    }
                }
            })
        },
        async ShowDeleteModal(Id) {
            await this.$PostDelete(`/CheckSetting/Delete`, { Id: Id });
            this.$refs.tableId.reload();
        },
        async ShowBatchDeleteModal() {
            var ids = this.$refs.tableId.GetSelectionRow().map(x => x.Id);
            await this.$PostDelete(`/CheckSetting/BatchDelete`, { Ids: ids });
            this.$refs.tableId.reload();
        },
        async TableSearch() {
            this.$refs.tableId.reload(this.searchForm);
        },
        async Reset() {
            this.searchForm = {};
            this.$refs.tableId.reload(this.searchForm);
        },
        updateEndDate() {
            // Automatically set EndDate to be the same as BeginDate initially
            if (this.formData.BeginDate) {
                this.formData.EndDate = this.formData.BeginDate; // Set EndDate to BeginDate
            } else {
                this.formData.EndDate = null; // Reset if BeginDate is cleared
            }
        },
        async showCheckStatDialog(CheckSetting) {
            this.currentCheckSettingId = CheckSetting.Id;
            this.currentOraganizationId = CheckSetting.OrganizationId;
            let { Data } = await this.$Post(`/User/GetCheckStat`, { OrganizationId: CheckSetting.OrganizationId, CheckSettingId: CheckSetting.Id });
            this.checkStatList = Data;
            this.checkStatDialogVisible = true;
            this.activeTab = 'all';
        },
        handleTabClick() {
            // Tab切换时不需要额外处理，因为使用计算属性自动过滤
        },
        showQRCode(row) {
            this.currentQRCode = row.CheckContent;
            this.qrcodeDialogVisible = true;
        },
        showStatusChangeDialog(user) {
            this.currentEditingUser = user;
            this.currentEditingUser.CheckSettingId = this.currentCheckSettingId;
            this.currentEditingUser.OrganizationId = this.currentOraganizationId;
            this.statusChangeDialogVisible = true;
        },
        async submitStatusChange() {
            try {
                this.currentEditingUser.CheckStatus = this.statusChangeForm.newStatus;
                await this.$Post('/CheckRecord/ChangeCheckStatus', this.currentEditingUser);
                this.$message.success('状态修改成功');
                this.statusChangeDialogVisible = false;
            } catch (error) {
                this.$message.error('状态修改失败：' + error.message);
            }
        },
        async exportCheckDatas() {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            let { Data } = await this.$Post(`/CheckRecord/List`, { CheckSettingId: this.currentCheckSettingId, CheckDateRange: `${year}-${month}-${day}`});
            // 执行导出逻辑
            const items = Data.Items;
            if (!items || items.length === 0) {
                this.$message.warning('没有数据可导出');
                return;
            }

            // 准备导出的数据
            const excelData = items.map(item => {
                return {
                    '用户ID': item.UserId || '',
                    '用户姓名': item.UserDto?.Name || '',
                    '班级ID': item.OrganizationId || '',
                    '班级名称': item.OrganizationDto?.Name || '',
                    '经度': item.Longitude || '',
                    '纬度': item.Latitude || '',
                    '打卡时间': item.CheckDate || '',
                    '是否迟到': item.IsLate ? '是' : '否',
                    '有效开始时间': item.BeginTime || '',
                    '有效截止时间': item.EndTime || '',
                    '人脸图片URL': item.FaceImageUrl || '',
                    '创建时间': item.CreationTime || '',
                    '创建人ID': item.CreatorId || ''
                };
            });

            // 创建工作簿
            const workbook = XLSX.utils.book_new();
            const worksheet = XLSX.utils.json_to_sheet(excelData);

            // 设置列宽（可选）
            const colWidths = [
                { wch: 10 }, // 用户ID
                { wch: 15 }, // 用户姓名
                { wch: 10 }, // 班级ID
                { wch: 15 }, // 班级名称
                { wch: 12 }, // 经度
                { wch: 12 }, // 纬度
                { wch: 20 }, // 打卡时间
                { wch: 10 }, // 是否迟到
                { wch: 20 }, // 有效开始时间
                { wch: 20 }, // 有效截止时间
                { wch: 40 }, // 人脸图片URL
                { wch: 20 }, // 创建时间
                { wch: 12 }  // 创建人ID
            ];
            worksheet['!cols'] = colWidths;

            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet, '打卡记录');

            // 生成Excel文件并下载
            const excelBuffer = XLSX.write(workbook, {
                bookType: 'xlsx',
                type: 'array',
                cellStyles: true // 启用样式
            });

            const blob = new Blob([excelBuffer], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });

            // 生成文件名，包含当前日期时间
            const now = new Date();
            const dateStr = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
            FileSaver.saveAs(blob, `打卡记录_${dateStr}.xlsx`);

            this.$message.success('导出成功');
        }
    },
};
</script>

<style>
    .check-stat-container {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        padding: 20px;
    }
    .user-stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 120px;
    }
    .avatar-container {
        position: relative;
        margin-bottom: 8px;
    }
    .stat-badge {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        border: 2px solid #fff;
    }
    .stat-badge.checked {
        background-color: #67C23A;
    }
    .stat-badge.unchecked {
        background-color: #F56C6C;
    }
    .stat-badge.late {
        background-color: #E6A23C;
    }
    .stat-badge.early-leave {
        background-color: #909399;
    }
    .user-name {
        font-size: 14px;
        margin-bottom: 4px;
        color: #606266;
    }
    .stat-info {
        font-size: 12px;
        color: #909399;
        text-align: center;
    }
    .stat-info > div {
        margin: 2px 0;
    }
</style>